<?php
namespace app\faxing\channel;


use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Qiqi23 extends FaXingBase
{

    public function register($params)
    {

        $cid = $this->cid;

        $sign = $params['sign'];
        $sign_data = [
            'appId'=> $this->extdata['appid'],
            'userId'=> $params['userId'],
//            'userName'=> $params['userName'],
            'time'=> $params['time'],
        ];

        $check_sign = $this->signData($sign_data,$this->extdata['APPKEY']);
        if($check_sign != $sign){
            $this->error("签名错误");
        }

        $account = $cid."_".$params['userId'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            $data['is_age'] = 0;

            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        $player['third_data'] = $params;
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];
    }


    public function order($order)
    {
        $role = PlayerRole::where(['gid'=>$order['gid'],'uid'=>$order['uid'],'cid'=>$order['cid']])->find();

        $account = get_player($order['uid'],'account');
        $account = explode("_",$account);
        $sign = get_sign(['order_no'=>$order['order_no']],$this->extdata['APPKEY']); // 回传验证
        $time = time();
        $data = [
            'userId' => $account[1],
            'gameId' => $this->extdata['gameid'],
            'goodsId'=> (string) rand(000000,999999),//商品id
            'goodsName'=>$order['goods_name'],//商品名称
            'money'=> (string) $order['amount'],//金额 整数：分
            'egretOrderId' => $order['order_no'],// 游戏方订单号
            'channelExt'=> "", // $order['order_no']."|".$sign 回传验证
            'ext'=> $order['order_no']."=".$sign, //  回传验证
            'time' =>(string) $time,
            'agentid' => $this->extdata['agentid'],
        ];

        $sign_data = [
            'egretOrderId' => $data['egretOrderId'],
            'gameId' => $data['gameId'],
            'goodsId'=> $data['goodsId'],
            'money'=> $data['money'],
            'time'=> $data['time'],
            'userId'=> $data['userId'],
            'appId'=> $this->extdata['appid']
        ];

        $data['sign'] = $this->signData($sign_data,$this->extdata['APPKEY']);
        return $data;
    }

    public function check_order($params)
    {
        $ord_arr = explode("=",$params['ext']);
        $order_no = $ord_arr[0];
        $sign = $ord_arr[1];
        // 双重校验
        $order_sign = get_sign(['order_no'=>$order_no],$this->extdata['APPKEY']);

        if($order_sign != $sign){
            echo "errorSign";exit;
        }

        if(!$this->check_sign($params,$this->extdata['APPKEY'])){
            echo "errorSign";exit;
        }

        // 查询订单
        $order = Order::where([
            'order_no'=>$order_no
        ])->find();


        if($order['amount'] != $params['money']){
            echo "error";exit;
        }

        $order->trade_no = $params['orderId'];
        $order->save();

        return $order;
    }

    public function create_role($params)
    {
        $url = "https://sdkapi.duoyou.com/games/role?";

        $redis = new Redis();
        $player = $redis->get($params['token']);
        $third_data = $player['third_data'];
        $account = explode("_",$player['account']);
        $data = [
            'app_id' => $this->extdata['APPID'],
            'user_id' => $account[1],
            'zone_id' =>(int) $params['sid'],
            'zone_name' => $params['sid'],
            'role_id' => $params['role_id'],
            'role_name' => $params['role_name'],
            'role_level' => $params['role_level'],
            'vip_level' => "0",
            'power' => $params['role_power'],
            'rebirth_times' => "0",
            'extra' => ""
        ];
        $data['sign'] = $this->signData($data,$this->extdata['APPKEY']);
        $data['push'] = 1;
        $res = file_get_contents($url.http_build_query($data));
        echo $res;exit;
    }


    public function message($message,$order)
    {
        echo $message === 'success' ? "success" :  "error";
        exit;
    }

    private function signData($data, $secret) {
        ksort($data);
        foreach ($data as $k => $v) {
            $tmp[] = $k . '=' . urlencode($v);
        }
        $str = urldecode(implode('', $tmp) . $secret);

        return md5($str);
    }

    protected function check_sign($params, $key)
    {
        $sign_data = $params;
        unset($sign_data['cid']);
        unset($sign_data['gid']);
        $sign = $sign_data['sign'];
        unset($sign_data['sign']);

        $check_sign = $this->signData($sign_data,$key);
        if($check_sign != $sign){
            return false;
        }
        return true;
    }

}